<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
        >新增
        </el-button>
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </div>
      <div class="right-panel">
        <jcx-table-bar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></jcx-table-bar>
      </div>
    </el-header>

    <el-main>
      <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="租户名称" prop="tenantName">
              <el-input
                  v-model="queryParams.tenantName"
                  placeholder="请输入租户名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="租户状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择租户状态" clearable>
                <el-option key="1" label="启用" :value="true"/>
                <el-option key="0" label="停用" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table ref="table" v-loading="loading" :data="tenantList" row-key="tenantId"
                @selection-change="handleSelectionChange"
                :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="租户标识" align="center" prop="tenantCode" v-if="columns[0].visible"></el-table-column>
        <el-table-column label="租户名称" align="center" prop="tenantName" v-if="columns[1].visible"></el-table-column>
        <el-table-column label="数据源标识" align="center" prop="sourceCode" v-if="columns[2].visible"></el-table-column>
        <el-table-column label="租户负责人" align="center" prop="platformUserName"
                         v-if="columns[3].visible"></el-table-column>
        <el-table-column label="联系电话" align="center" prop="phone" v-if="columns[4].visible"></el-table-column>
        <el-table-column label="联系邮箱" align="center" prop="email" v-if="columns[5].visible"></el-table-column>
        <el-table-column label="租户系统开始时间" align="center" prop="startDate" v-if="columns[6].visible">
          <template #default="props">
            <span>{{ $TOOL.dateFormat(props.row.startDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="租户系统到期时间" align="center" prop="endDate" v-if="columns[7].visible">
          <template #default="props">
            <span>{{ $TOOL.dateFormat(props.row.endDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[8].visible">
          <template #default="props">
            <el-tag v-if="props.row.status" type="success">启用</el-tag>
            <el-tag v-if="!props.row.status" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[9].visible"></el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[10].visible"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="props">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(props.row)"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(props.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog destroy-on-close append-to-body width="900px" :title="title" v-model="open"
                 :close-on-click-modal="false" @closed="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <div style="text-align: center;">
                <span v-if="imgUrl === null">待上传 Logo</span>
                <el-image
                    v-else
                    style="width: 100px; height: 100px"
                    :src="imgUrl"
                    :zoom-rate="1.2"
                    :initial-index="4"
                    fit="cover"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租户Logo" prop="logoUrl">
                <el-upload
                    ref="upload"
                    :limit="1"
                    accept=".jpg, .png"
                    :action="upload.url"
                    :headers="upload.headers"
                    :file-list="upload.fileList"
                    :on-preview="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :on-remove="handleRemoveFile"
                    :auto-upload="false">
                  >
                  <template #trigger>
                    <el-button type="primary">选取文件</el-button>
                  </template>
                  <el-button class="ml-3" type="success" @click="handleSubmitUpload">
                    上传文件
                  </el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传jpg/png文件，且不超过500kb
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数据源ID" prop="sourceId">
                <el-input v-model="form.sourceId" clearable placeholder="请输入数据源ID" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据源标识" prop="sourceCode">
                <el-select style="width: 100%" v-model="form.sourceCode" placeholder="请选择数据源标识" clearable
                           @change="sourceCodeChange"
                           :disabled="form.tenantId !== '' && form.tenantId !== null">
                  <el-option
                      v-for="data in dataList"
                      :key="data.sourceId"
                      :label="data.sourceName"
                      :value="data.sourceCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="租户标识" prop="tenantCode">
                <el-input v-model="form.tenantCode" clearable placeholder="请输入租户标识"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租户名称" prop="tenantName">
                <el-input v-model="form.tenantName" clearable placeholder="请输入租户名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" clearable placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系邮箱" prop="email">
                <el-input v-model="form.email" clearable placeholder="请输入部门邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="租户负责人" prop="platformUserId">
                <el-select v-model="form.platformUserId" placeholder="请选择" style="width: 100%;">
                  <el-option
                      v-for="user in userList"
                      :key="user.userId"
                      :label="user.nickName"
                      :value="user.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否有效" prop="status">
                <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startDate">
                <el-date-picker clearable
                                style="width: 100%"
                                v-model="form.startDate"
                                type="datetime"
                                placeholder="系统开始时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期时间" prop="endDate">
                <el-date-picker
                    clearable
                    style="width: 100%"
                    v-model="form.endDate"
                    type="datetime"
                    placeholder="系统到期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" clearable placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button type="primary" :loading="saveing" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "Tenant",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 保存遮罩层
      saveing: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 租户列表数据
      tenantList: [],
      // 用户列表
      userList: [],
      // 数据源列表
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        tenantName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantCode: [
          {required: true, message: '请输入租户标识', trigger: 'blur'}
        ],
        tenantName: [
          {required: true, message: '请输入租户名称', trigger: 'blur'}
        ],
        sourceCode: [
          {required: true, message: '请输入数据源标识', trigger: 'blur'}
        ],
        platformUserId: [
          {required: true, message: '请选择租户负责人', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择是否启用', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入联系邮箱', trigger: 'blur'}
        ],
        startDate: [
          {required: true, message: '请选择系统开始时间', trigger: 'blur'}
        ],
        endDate: [
          {required: true, message: '请选择系统到期时间', trigger: 'blur'}
        ]
      },
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      columns: [
        {key: 0, label: `租户标识`, visible: true},
        {key: 1, label: `租户名称`, visible: true},
        {key: 2, label: `数据源标识`, visible: true},
        {key: 3, label: `租户负责人`, visible: true},
        {key: 4, label: `联系电话`, visible: true},
        {key: 5, label: `联系邮箱`, visible: true},
        {key: 6, label: `租户系统开始时间`, visible: true},
        {key: 7, label: `租户系统到期时间`, visible: true},
        {key: 8, label: `状态`, visible: true},
        {key: 9, label: `创建时间`, visible: false},
        {key: 10, label: `备注`, visible: true}
      ],
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: this.$TOOL.getJti()},
        // 上传的地址
        url: this.$CONFIG.API_URL + "/platform/file/uploadImage",
        // 上传的文件列表
        fileList: []
      },
      imgUrl: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      if (this.userList.length === 0) {
        this.$API.user.pageListUser.get({status: true}).then(response => {
          if (response.status) {
            this.userList = response.data.records;
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      if (this.dataList.length === 0) {
        this.$API.dataSource.pageListDataSource.get({status: true}).then(response => {
          if (response.status) {
            this.dataList = response.data.records;
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      this.$API.tenant.pageListTenant.get(this.queryParams).then(response => {
        if (response.status) {
          this.tenantList = response.data.records
        } else {
          this.$message.warning(response.msg);
        }
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tenantId: "",
        tenantCode: "",
        tenantName: "",
        sourceId: "",
        sourceCode: "",
        platformUserId: "",
        phone: "",
        email: "",
        logoUrl: "",
        startDate: "",
        endDate: "",
        remark: "",
        status: true,
        url: "",
        username: "",
        password: ""
      };
      this.upload.fileList = [];
      this.imgUrl = null;
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加租户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tenantId = row.tenantId || this.ids
      this.$API.tenant.getTenantById.get(tenantId).then(response => {
        if (response.status) {
          this.form = response.data;
          if (this.form.logoUrl) {
            this.imgUrl = this.form.logoUrl
            this.upload.fileList = [{name: '租户 Logo', url: this.form.logoUrl}];
          }
          this.open = true;
          this.title = "修改租户";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    sourceCodeChange(sourceCode) {
      for (let i = 0; i < this.dataList.length; i++) {
        if (sourceCode === this.dataList[i].sourceCode) {
          this.form.sourceId = this.dataList[i].sourceId
          this.form.url = this.dataList[i].url
          this.form.username = this.dataList[i].username
          this.form.password = this.dataList[i].password
          return;
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.tenantId) {
            this.$API.tenant.editTenant.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.tenant.addTenant.post(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tenantIds = row.tenantId ? [row.tenantId] : this.ids;
      this.$confirm(`确定删除选中的 ${tenantIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.tenant.delTenants.delete(tenantIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    },
    // 文件提交处理
    handleSubmitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.logoUrl = response.data.fileUrl;
      this.imgUrl = response.data.fileUrl
      this.$message.success(response.msg);
    },
    handleRemoveFile() {
      this.imgUrl = null
    }
  }
};
</script>

<style scoped>

</style>
